<?php
/**
 * Created by PhpStorm.
 * User: rocky
 * Date: 2022-05-30
 * Time: 22:22
 */

namespace plugin\thinkphp\service;


use ExAdmin\ui\contract\MenuAbstract;
use plugin\thinkphp\Admin;

class Menu extends MenuAbstract
{
    protected $model;

    public function __construct()
    {
        $this->model = plugin()->thinkphp->config('database.menu_model');
    }
    /**
     * 菜单
     * @return array
     */
    public function all(): array
    {

        return $this->model::where('status',1)
            ->when(plugin()->thinkphp->config('admin_auth_id') != Admin::id(),function ($query){
                $model = plugin()->thinkphp->config('database.role_menu_model');
                $menuIds = $model::whereIn('role_id',Admin::role())->column('menu_id');
                $query->whereIn('id',$menuIds);
            })
            ->order('sort')->select()->toArray();
    }

    /**
     * 创建菜单
     * @param array $data
     * @return int
     */
    public function create(array $data):int
    {
        $result = $this->model::create($data);
        return $result->id;
    }
    /**
     * 获取菜单
     * @param array $data
     * @return array
     */
    public function get($id){
        return $this->model::find($id)->toArray();
    }
    /**
     * 更新菜单
     * @param int $id
     * @param array $data
     * @return mixed
     */
    public function update($id,$data){
        $this->model::where('id',$id)->update($data);
    }
    /**
     * 启用菜单
     * @param $plugin
     * @return mixed
     */
    public function enable($plugin)
    {
        $this->model::where('plugin',$plugin)->update(['status'=>1]);
    }

    /**
     * 禁用菜单
     * @param $plugin
     * @return mixed
     */
    public function disable($plugin)
    {
        $this->model::where('plugin',$plugin)->update(['status'=>0]);
    }

    /**
     * 删除菜单
     * @param $plugin
     * @return mixed
     */
    public function delete($plugin)
    {
        $this->model::where('plugin',$plugin)->delete();
    }
}
